package com.xncoding.tomcat.socket02;

import com.xncoding.tomcat.socket01.HttpProtocolUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 提取了一些共用类和函数
 */
public class ResourceUtil {

    /**
     * 根据请求 url 获取完整绝对路径
     */
    public static String getPath(String url) {
        String path = ResourceUtil.class.getResource("/").getPath();
        return path.replaceAll("\\\\", "/") + url;
    }

    /**
     * 输出静态资源信息
     */
    public static void outputResource(InputStream input, OutputStream output) throws IOException {
        int count = 0;
        while (count == 0) {
            count = input.available();
        }
        int resourceSize = count;
        output.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());
        long written = 0;
        int byteSize = 1024;
        byte[] bytes = new byte[byteSize];
        while (written < resourceSize) {
            if (written + byteSize > resourceSize) {
                byteSize = (int) (resourceSize - written);
                bytes = new byte[byteSize];
            }
            input.read(bytes);
            output.write(bytes);
            output.flush();
            written += byteSize;
        }
    }
}
